<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="visible = $event"
    :title="isEdit ? '编辑岗位' : '发布新岗位'"
    width="900px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="岗位名称" prop="jobName">
        <el-input v-model="formData.jobName" placeholder="请输入岗位名称" maxlength="50" show-word-limit />
      </el-form-item>

      <el-form-item label="岗位描述" prop="jobDescription">
        <el-input v-model="formData.jobDescription" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请填写岗位职责与内容" />
      </el-form-item>

      <el-form-item label="岗位要求" prop="jobRequirements">
        <el-input v-model="formData.jobRequirements" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请填写任职要求（学历/经验/技能）" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作地点" prop="location">
            <el-input v-model="formData.location" placeholder="请输入工作地点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资范围" prop="salary">
            <el-input v-model="formData.salary" placeholder="请输入薪资范围" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作经验" prop="experience">
            <el-select v-model="formData.experience" placeholder="请选择工作经验要求">
              <el-option label="不限" value="不限" />
              <el-option label="1年以下" value="1年以下" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-5年" value="3-5年" />
              <el-option label="5-10年" value="5-10年" />
              <el-option label="10年以上" value="10年以上" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学历要求" prop="education">
            <el-select v-model="formData.education" placeholder="请选择学历要求">
              <el-option label="不限" value="不限" />
              <el-option label="高中及以下" value="高中及以下" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="岗位分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择岗位分类">
              <el-option label="技术开发" value="技术开发" />
              <el-option label="产品运营" value="产品运营" />
              <el-option label="市场销售" value="市场销售" />
              <el-option label="人力资源" value="人力资源" />
              <el-option label="财务审计" value="财务审计" />
              <el-option label="行政后勤" value="行政后勤" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="招聘人数" prop="hiringCount">
            <el-input-number v-model="formData.hiringCount" :min="1" :max="100" placeholder="招聘人数" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="岗位状态" prop="jobStatus">
        <el-select v-model="formData.jobStatus" placeholder="请选择岗位状态">
          <el-option label="招聘中" value="active" />
          <el-option label="已暂停" value="inactive" />
          <el-option label="已结束" value="closed" />
        </el-select>
      </el-form-item>

      <el-descriptions v-if="isEdit" :column="2" border>
        <el-descriptions-item label="岗位编号">{{ formData.jobId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="企业编号">{{ formData.enterpriseId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formData.createTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formData.updateTime || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ isEdit ? '更新' : '发布' }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createJob, updateJob } from '@/api/enterprise'
import useStore from '@/store'

const store = useStore()

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  jobData: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.jobData?.jobId)

const formRef = ref()
const loading = ref(false)

const formData = reactive({
  jobId: '',
  enterpriseId: '',
  jobName: '',
  jobDescription: '',
  jobRequirements: '',
  location: '北京',
  salary: '面议',
  experience: '不限',
  education: '不限',
  category: '技术开发',
  hiringCount: 1,
  jobStatus: 'active',
  createTime: '',
  updateTime: ''
})

const formRules = {
  jobName: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度 2-50 个字符', trigger: 'blur' }
  ],
  jobDescription: [
    { required: true, message: '请输入岗位描述', trigger: 'blur' },
    { min: 10, max: 1000, message: '长度 10-1000 个字符', trigger: 'blur' }
  ],
  jobRequirements: [
    { required: true, message: '请输入岗位要求', trigger: 'blur' },
    { min: 10, max: 1000, message: '长度 10-1000 个字符', trigger: 'blur' }
  ],
  jobStatus: [
    { required: true, message: '请选择岗位状态', trigger: 'change' }
  ]
}

watch(visible, (val) => { if (val) initForm() })

function initForm() {
  if (isEdit.value) {
    Object.keys(formData).forEach((k) => { formData[k] = props.jobData?.[k] ?? formData[k] })
  } else {
    // 重置为新岗位的默认值
    Object.assign(formData, {
      jobId: '',
      enterpriseId: '',
      jobName: '',
      jobDescription: '',
      jobRequirements: '',
      location: '北京',
      salary: '面议',
      experience: '不限',
      education: '不限',
      category: '技术开发',
      hiringCount: 1,
      jobStatus: 'active',
      createTime: '',
      updateTime: ''
    })
  }
}

function handleClose() {
  visible.value = false
  formRef.value?.resetFields?.()
}

async function handleSubmit() {
  try {
    await formRef.value?.validate?.()
    loading.value = true
    
    // 获取当前企业ID
    const currentEnterpriseId = store.app.enterpriseId
    
    if (!currentEnterpriseId) {
      ElMessage.error('未找到企业信息，请先登录')
      loading.value = false
      return
    }
    
    // 准备提交数据
    const submitData = {
      enterpriseId: isEdit.value ? formData.enterpriseId : currentEnterpriseId, // 编辑时使用原有ID，创建时使用当前登录企业ID
      jobName: formData.jobName,
      jobDescription: formData.jobDescription,
      jobRequirements: formData.jobRequirements,
      location: formData.location,
      salary: formData.salary,
      experience: formData.experience,
      education: formData.education,
      category: formData.category,
      hiringCount: formData.hiringCount,
      jobStatus: formData.jobStatus
    }
    
    console.log('📝 提交岗位数据:', submitData)
    console.log('🏢 当前企业ID:', currentEnterpriseId)
    
    if (isEdit.value) {
      // 更新岗位
      await updateJob(formData.jobId, submitData)
      ElMessage.success('岗位更新成功')
      emit('success')
      handleClose()
    } else {
      // 创建岗位
      const response = await createJob(submitData)
      ElMessage.success('岗位发布成功')
      
      // 发布成功后，将新创建的岗位数据传递给父组件
      emit('success', response.data)
      
      // 发布成功后关闭对话框，回到主页面
      handleClose()
    }
  } catch (e) {
    console.error('提交失败:', e)
    console.error('错误详情:', e.response || e.message)
    ElMessage.error(e.message || e.response?.data?.message || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer { text-align: right; }
</style>